/*
 * @Author: yanjikun
 * @Date: 2021-11-04 16:39:04
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-06-13 14:18:11
 * @Description: file content
 */
import { login } from '@/api/login'
import { ACCESS_TOKEN, TENANT, USER_INFO } from '@/enums/cacheEnums'
import { generatorDynamicRouter } from '@/router/generator-routers'
import { storage } from '@/utils/Storage'
import { defineStore } from 'pinia'
import { resetRouter } from '@/router'
import { useSocketStore } from './socket'
import { RouteRecordRaw } from 'vue-router'
const UserState = {
  token: '',
  loading: false,
  tenant: 0,
  info: null as API.UserInfo | null,
  menus: [] as RouteRecordRaw[],
}
type IUserState = typeof UserState
export const useUserStore = defineStore({
  id: 'user',
  state: (): IUserState => UserState,
  getters: {
    getLoading(): boolean {
      return this.loading
    },
    getToken(): () => string {
      return () => this.token || (storage.get(ACCESS_TOKEN) as string)
    },
    getTenant(): () => number {
      return () => this.tenant || (storage.get(TENANT, 0) as number)
    },
    getUserInfo(): () => API.UserInfo {
      return () => this.info ?? storage.get(USER_INFO)
    },
    getMenus(): () => RouteRecordRaw[] {
      return () => this.menus
    },
  },
  actions: {
    /** 清空token及用户信息 */
    resetToken() {
      this.token = ''
      this.tenant = 0
      this.info = null
      this.menus = []
      storage.clear()
    },
    setLoading(loading: boolean) {
      this.loading = loading
    },
    /**设置token */
    setToken(token: string) {
      this.token = token ?? ''
      const expire = 7 * 24 * 60 * 60
      storage.set(ACCESS_TOKEN, this.token, expire)
    },
    /**设置租户 */
    setTenant(tenant: number) {
      this.tenant = tenant ?? ''
      const expire = 7 * 24 * 60 * 60
      storage.set(TENANT, this.tenant, expire)
    },
    /**设置用户信息 */
    setUserInfo(info: API.UserInfo) {
      this.info = info
      storage.set(USER_INFO, this.info)
    },
    /**登录 */
    async login(params: API.LoginParams) {
      try {
        const data = await login(params)
        this.setToken(data.token)
        this.setTenant(data.org)
        this.setUserInfo(data)
        return this.afterLogin()
      } catch (error) {
        return Promise.reject(error)
      }
    },
    async afterLogin() {
      try {
        // const socketStore = useSocketStore()
        const routers = await generatorDynamicRouter()
        this.menus = routers
        // !socketStore.trackerService && socketStore.initSocket()
        return routers
      } catch (error) {
        console.log(error)
        this.logout()
        return Promise.reject(error)
      }
    },
    /**登出 */
    async logout() {
      const socketStore = useSocketStore()
      socketStore.closeSocket()
      this.resetToken()
      resetRouter()
    },
  },
})
